<template>
  <div ref="appRef" class="my-container-box">
    <div id="btnItem" class="title-box df aic jcsb">
      <div class="title">{{ state.title }}</div>
      <div v-if="state.isExport" class="btn" @click="handleExport()">
        <i class="iconfont icon-daochu"></i>导出
      </div>
    </div>

    <div>
      <el-date-picker
        v-if="state.isDaQueryT"
        v-model="startDate"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :size="size"
        @change="changeDatePicker"
      />
      <el-date-picker
        v-else
        v-model="startDate"
        type="date"
        placeholder="请选择查询日期"
        :size="size"
        @change="changeDatePicker"
      />
    </div>
    <div class="pt-4">
      <table-page-content
        :table-data="state.tableList"
        :table-headers="state.tableHeaders"
        :is-slot-num="false"
        :is-pager="false"
        :table-height="tableHeight"
        :is-more-header="true"
        :lazy-tree="true"
        :expand-all="false"
        :tree-props="{ children: 'children', hasChildren: 'haveChildren' }"
        @handle-lazy-load="getChildNode"
        @handle-expent-change="expentChange"
      >
      </table-page-content>
    </div>
    <export-component
      ref="exportRef"
      :title="state.title"
      :area-code-list="state.areaCodeList"
      :user-type="state.userType"
      :table-title="state.title"
    ></export-component>
  </div>
</template>

<script setup lang="ts" name="TableList">
import { useTableHeight } from '@/hooks/tableHeight'
import useMenuStore from '@/store/modules/menu'
import useUserStore from '@/store/modules/user'
import exportComponent from './components/export.vue'
import { getTableDataDetail } from './api'
import { useProxy } from '@/utils/proxy'
import dayjs from 'dayjs'
const exportRef = ref()
const { proxy } = useProxy()
const menuStore = useMenuStore()
const userStore = useUserStore()
const menus = computed(() => menuStore.sidebarRouters)
const { appRef, tableHeight } = useTableHeight(true)
const tableId = proxy.$route.params && (proxy.$route.params.tableId as string)
const size = ref<'default' | 'large' | 'small'>('default')
const startDate: any = ref('')
const state = reactive({
  title: '报表统计',
  userType: userStore.userInfo.userType as string,
  isExport: false,
  areaCodeList: [] as any[],
  tableHeaders: [] as any[],
  tableList: [] as any[],
  DatEQuery: {},
  isDaQueryT: !true
})
// 区域时间选择
const changeDatePicker = async (event: any) => {
  console.log(event)
  if (event) {
    if (state.isDaQueryT) {
      state.DatEQuery = {
        startDate: dayjs(startDate._rawValue[0]).format('YYYY-MM-DD'),
        endDate: dayjs(startDate._rawValue[1]).format('YYYY-MM-DD')
      }
    } else {
      state.DatEQuery = {
        startDate: dayjs(startDate._rawValue[0]).format('YYYY-MM-DD')
      }
    }
  } else {
    console.log(event)
  }

  console.log(event)

  getTableDetail()
}
// 获取根节点数据
const getTableDetail = () => {
  getTableDataDetail(tableId, { allArea: false, areaCode: ' ', ...state.DatEQuery }).then((res) => {
    state.tableHeaders = setTableHeader(res.data.reportHeaders || [])
    state.tableList =
      res.data?.data?.length > 0
        ? res.data.data.map((v: any) => {
            v.haveChildren = true
            v.level = 1
            return v
          })
        : []
    state.title = res.data.reportTitle || ''
  })
}
// 获取下级数据
const getChildNode = (row: any, node: any, resolve: any) => {
  let params = {} as any
  if (row.level == 1) {
    params = {
      allArea: state.userType == '0' ? false : true,
      areaCode: state.userType == '0' ? row.areaCode : ' '
    }
  } else {
    params = row?.corporationCode
      ? {
          allArea: false,
          areaCode: row.parentAreaCode,
          corporationCode: row.corporationCode
        }
      : {
          allArea: false,
          areaCode: row.areaCode || ' '
        }
  }
  getTableDataDetail(tableId, params).then((res) => {
    params = { ...state.DatEQuery, ...params }
    let treeArr =
      res.data?.data?.length > 0
        ? res.data.data.map((v: any, i: number) => {
            v.parentAreaCode = row.areaCode ?? ''
            v.level = row.level + 1
            return v
          })
        : []
    resolve(treeArr)
  })
}
// 处理表格头
const setTableHeader = (treeData: any[]) => {
  treeData.forEach((v) => {
    if (v?.children?.length) {
      if (v.isSum == '1') {
        let item = {
          cellName: '小计',
          isSumItem: true,
          cellWidth: 100,
          cellAlignment: 'center',
          cellDataKey: modTreeGetKey(v.children, []).join(',')
        } as any
        v.sumPosition == '0' ? v.children.unshift(item) : v.children.push(item)
      }
      setTableHeader(v.children)
    }
  })
  let defaultArr = [
    {
      cellName: '企业名称',
      isSumItem: false,
      cellWidth: 200,
      cellAlignment: 'left',
      cellDataKey: 'enterpriseId'
    },
    {
      cellName: '企业类型',
      isSumItem: false,
      cellWidth: 100,
      cellAlignment: 'left',
      cellDataKey: 'enterpriseType'
    },
    {
      cellName: '区域编码',
      isSumItem: false,
      cellWidth: 100,
      cellAlignment: 'left',
      cellDataKey: 'areaCodeDescr'
    }
  ]
  return defaultArr.concat(treeData)
}
//遍历树寻找小计根节点
const modTreeGetKey = (treeData: any[], keyArr: string[]) => {
  treeData.forEach((item: any) => {
    if (item?.children?.length) {
      modTreeGetKey(item.children, keyArr)
    } else {
      keyArr.push(item.cellDataKey)
    }
  })
  return keyArr
}
//获取权限
const getPower = () => {
  let menuItem = menus.value.filter((v: any) => v.path == '/tableData/index')[0] as any
  let index = menuItem.children.findIndex((v: any) => v.path == proxy.$route.fullPath)
  if (index != -1) {
    const rights = menuItem.children[index].meta.rights as any[]
    if (!rights?.length) {
      state.isExport = true
    } else {
      const hasPermission = rights.some((item: any) => {
        return item.meta.permissionKey.includes('export')
      })
      state.isExport = hasPermission ? true : false
    }
  }
}
// 展开行回调
const expentChange = (row: any, expend: boolean) => {
  let index = state.areaCodeList.findIndex((v) => v.id == row.id)
  if (index == -1) {
    state.areaCodeList.push({
      id: row.id,
      level: row.level,
      areaCode: row.areaCode,
      corporationCode: row?.corporationCode,
      parentAreaCode: row?.parentAreaCode,
      expend
    })
  } else {
    state.areaCodeList[index].expend = expend
  }
}
// 导出
const handleExport = () => {
  exportRef.value.state.tableId = tableId
  exportRef.value.state.show = true
}
getPower()
getTableDetail()
</script>

<style lang="scss" scoped>
.pt-4 {
  padding-top: 10px;
}
.title-box {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}
.title {
  font-size: 20px;
  color: #666666;
  box-sizing: border-box;
}
.btn {
  height: 30px;
  background: rgba(85, 141, 247, 0.1);
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid $blue;
  padding: 0px 9px;
  text-align: center;
  line-height: 30px;
  color: $blue;
  font-size: 16px;
  cursor: pointer;
  .iconfont {
    margin-right: 4px;
    font-size: 13px;
    margin-bottom: 1px;
  }
}
</style>
